<template>
  <j-modal :title="title" :width="width" :visible="visible" :confirmLoading="confirmLoading" :maskClosable="false"
    :keyboard="false" v-bind:prefixNo="prefixNo" switchHelp okText='保存' switchFullscreen @ok="handleOk"
    @cancel="handleCancel" wrapClassName="ant-modal-cust-warp" :id="prefixNo"
    style="top:5%;height: 110%;overflow-y: hidden">
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-row class="form-row" :gutter="24">
          <a-col :lg="6" :md="12" :sm="24">
            <!-- <a-form-item  label="渠道来源" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input placeholder="请输入渠道来源" v-decorator.trim="[ 'source', validatorRules.source]"/>
            </a-form-item> -->
            <a-form-item label="渠道来源" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-select placeholder="请输入渠道来源" v-decorator.trim="['source', validatorRules.source]"
                :dropdownMatchSelectWidth="false" showSearch optionFilterProp="children">
                <a-select-option v-for="(item, index) in sourceList" :key="index" :value="item.name">{{ item.name
                  }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item label="客户姓名" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input placeholder="请输入客户姓名" v-decorator.trim="['name', validatorRules.name]" />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item label="联系号码" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input placeholder="请输入联系号码" :maxLength="11" v-decorator.trim="['tel', validatorRules.tel]" />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item label="身份证号码" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input placeholder="请输入身份证号码" :maxLength="18"
                v-decorator.trim="['idNumber', validatorRules.idNumber]" />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item label="门店名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-select placeholder="请输入门店名称" v-decorator.trim="['storeName', validatorRules.storeName]"
                :dropdownMatchSelectWidth="false" showSearch optionFilterProp="children">
                <a-select-option v-for="(item, index) in storeNameList" :key="index" :value="item">{{ item
                  }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item label="地址" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input placeholder="请输入地址" v-decorator.trim="['address', validatorRules.address]" />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item label="业务员" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-select placeholder="请输入业务员" v-decorator.trim="['ope', validatorRules.ope]"
                :dropdownMatchSelectWidth="false" showSearch optionFilterProp="children">
                <a-select-option v-for="(item, index) in opeList" :key="index" :value="item.name">{{ item.name
                  }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item label="开单时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-date placeholder="请输入开单时间" v-model="model.startTime"
                v-decorator.trim="['startTime', validatorRules.startTime]"></j-date>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row class="form-row" :gutter="24">
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item label="业务类型" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-select placeholder="请输入业务类型" @change="changeType" v-decorator.trim="['type', validatorRules.type]"
                :dropdownMatchSelectWidth="false" showSearch optionFilterProp="children">
                <a-select-option v-for="(item, index) in typeList" :key="index" :value="item.name">{{ item.name
                  }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <!-- <a-col :lg="8" :md="12" :sm="24" v-show="(opeType == 1 || model.type != '回收') ? false : true"> -->
          <a-col :lg="8" :md="12" :sm="24">
            <a-form-item label="出货价/还款金额" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input placeholder="请输入出货价/还款金额" v-model="model.deliveryPrice"
                v-decorator.trim="['deliveryPrice', validatorRules.deliveryPrice]" />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <!-- <a-form-item label="操作时间" v-show="model.type !== '回收'" :labelCol="labelCol" :wrapperCol="wrapperCol"> -->
            <a-form-item label="操作时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-date placeholder="请输入操作时间" v-model="model.updateTime"></j-date>
            </a-form-item>
          </a-col>
        </a-row>
        <j-editable-table id="deliveryModal" :ref="refKeys[0]" :loading="materialTable.loading"
          :columns="materialTable.columns" :dataSource="materialTable.dataSource" :maxHeight="300" :rowNumber="false"
          :rowSelection="true" :actionButton="true" :dragSort="true" @valueChange="onValueChange" @deleted="onDeleted">
        </j-editable-table>
        <a-row class="form-row" :gutter="24" style="margin-top: 30px;">
          <a-col :lg="8" :md="12" :sm="24" v-show="model.type !== '回收'">
            <!-- v-decorator.trim="[ 'rate', validatorRules.rate]"  -->
            <a-form-item label="寄存时长服务费率" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-select placeholder="请输入寄存时长服务费率" @change="ChangeRate" v-model="model.rate"
                :dropdownMatchSelectWidth="false" showSearch optionFilterProp="children">
                <a-select-option v-for="(item, index) in rateList" :key="index" :value="item">{{ item
                  }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24" v-if="this.model.id" v-show="model.type !== '回收'">
            <a-form-item label="收益" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input placeholder="请输入收益" :read-only="rate.index < 3" v-model="model.profit" />
              <!-- <a-input placeholder="请输入收益"  :read-only="rate.index < 3" v-model="model.profit" :disabled="opeType == 4 ? true : false"/> -->
            </a-form-item>
          </a-col>
          <a-col :lg="10" :md="12" :sm="24" v-show="model.type !== '回收'">
            <a-form-item label="寄存到期时间记录/出货时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-date dateFormat="YYYY-MM-DD" v-model="model.endTime" :read-only="rate.index < 3"></j-date>
            </a-form-item>
          </a-col>
          <a-col :lg="11" :md="12" :sm="24">
            <a-form-item label="到期提醒" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-textarea :rows="7" placeholder="请输入到期提醒" v-decorator.trim="['reminder', validatorRules.reminder]" />
            </a-form-item>
          </a-col>
          <a-col :lg="11" :md="12" :sm="24">
            <a-form-item label="其他备注" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-textarea :rows="7" placeholder="请输入其他备注" v-decorator.trim="['remark', validatorRules.remark]" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row class="form-row" :gutter="24">
          <a-col :lg="15" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="业务图片">
              <j-image-upload v-model="fileList" v-decorator.trim="['fileName', validatorRules.fileName]"
                bizPath="business" text="上传" isMultiple></j-image-upload>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row class="form-row" :gutter="24">
          <a-col :lg="15" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="业务视频">
              <j-upload v-model="imgName" v-decorator.trim="['imgName', validatorRules.imgName]" bizPath="bill"
                isMultiple></j-upload>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row class="form-row" :gutter="24">
          <a-col :lg="15" :md="12" :sm="24">
            <a-form-item label="行情收益反馈" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-textarea :rows="7" placeholder="请输入其他备注" v-decorator.trim="['feedback', validatorRules.feedback]" />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-spin>
  </j-modal>
</template>
<script>
import pick from 'lodash.pick'
import { FormTypes } from '@/utils/JEditableTableUtil'
import { JEditableTableMixin } from '@/mixins/JEditableTableMixin'
import JUpload from '@/components/jeecg/JUpload'
import JDate from '@/components/jeecg/JDate'
import JSelectPosition from '@/components/jeecgbiz/JSelectPosition'
import JImageUpload from '../../../components/jeecg/JImageUpload'
import { getAction } from '@/api/manage'
import { VALIDATE_NO_PASSED } from '@/utils/JEditableTableUtil'

import Vue from 'vue'
import { BusinessMixin } from '../mixins/BusinessMixin'
export default {
  name: "BusinessModalUpdate",
  mixins: [JEditableTableMixin, BusinessMixin],
  components: {
    JUpload,
    JDate,
    JSelectPosition,
    JImageUpload
  },
  data() {
    return {
      title: "操作",
      width: '1600px',
      moreStatus: false,
      // 新增时子表默认添加几行空数据
      addDefaultRowNum: 1,
      visible: false,
      supList: [],
      depotList: [],
      columns: {
        other: [
          {
            title: '物品类型', key: 'category', width: '7%', type: FormTypes.select, placeholder: '请选择${title}',
            options: [],
            validateRules: [{ required: true, message: '${title}不能为空' }]
          },
          {
            title: '物品鉴定级别', key: 'level', width: '7%', type: FormTypes.select, placeholder: '请选择${title}',
            options: [],
            validateRules: [{ required: true, message: '${title}不能为空' }]
          },
          {
            title: '数量', key: 'amount', width: '7%', type: FormTypes.inputNumber,
            validateRules: [{ required: true, message: '${title}不能为空' }]
          },
          {
            title: '品牌,规格,重量', key: 'brandWeight', width: '30%', type: FormTypes.input,
            validateRules: [{ required: true, message: '${title}不能为空' }]
          },
          {
            title: '寄存金额', key: 'depositAmount', width: '10%', type: FormTypes.inputNumber, statistics: true,
            validateRules: [{ required: false, message: '${title}不能为空' }]
          },
          {
            title: '当日行情价', key: 'daily', width: '10%', type: FormTypes.input,
            validateRules: [{ required: false, message: '${title}不能为空' }]
          }
        ],
        recycle: [
          {
            title: '物品类型', key: 'category', width: '7%', type: FormTypes.select, placeholder: '请选择${title}',
            options: [],
            validateRules: [{ required: true, message: '${title}不能为空' }]
          },
          {
            title: '物品鉴定级别', key: 'level', width: '7%', type: FormTypes.select, placeholder: '请选择${title}',
            options: [],
            validateRules: [{ required: true, message: '${title}不能为空' }]
          },
          {
            title: '数量', key: 'amount', width: '7%', type: FormTypes.inputNumber,
            validateRules: [{ required: true, message: '${title}不能为空' }]
          },
          {
            title: '品牌,规格,重量', key: 'brandWeight', width: '30%', type: FormTypes.input,
            validateRules: [{ required: true, message: '${title}不能为空' }]
          },
          {
            title: '当日行情价', key: 'daily', width: '10%', type: FormTypes.input,
            validateRules: [{ required: false, message: '${title}不能为空' }]
          },
          {
            title: '回收单价', key: 'recyclePrice', width: '10%', type: FormTypes.inputNumber, defaultValue: '', statistics: true,
            validateRules: [{ required: false, message: '${title}不能为空' }]
          },
          {
            title: '回收总价', key: 'recycleTotal', width: '10%', type: FormTypes.inputNumber, readonly: true, defaultValue: '0', statistics: true,
            validateRules: [{ required: false, message: '${title}不能为空' }]
          }],
        credit: [
          {
            title: '寄存金额', key: 'depositAmount', width: '10%', type: FormTypes.inputNumber, statistics: true, readonly: true, defaultValue: '0',
            validateRules: [{ required: false, message: '${title}不能为空' }]
          }
        ]
      },
      rate: {
        option: [{ date: 1, rate: 3 }, { date: 10, rate: 5 }, { date: 30, rate: 10 }],
        currentRate: 0,
        index: -1
      },
      deposit: 0,
      profit: 0,
      operTimeStr: '',
      prefixNo: 'CGDD',
      sourceList: [],
      storeNameList: ['沙市玉桥店', '公安一店'],
      opeList: [],
      typeList: [],
      fileList: [],
      imgName: [],
      produceList: [],
      model: {
        startTime: '',
        endTime: '',
        profit: '',
        deliveryPrice: '',
        recycleTotal: '',
        amountCount: 0,
        updateTime: ''
      },
      opeType: 0,
      engineerId: "",
      rateList: ['1天-3%服务费率', '10天-5%服务费率', '一个月-10%服务费率', '综合服务费', '过桥5‰每天'],
      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      refKeys: ['materialDataTable',],
      tableKeys: ['materialDataTable',],
      activeKey: 'materialDataTable',
      materialTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '物品类型', key: 'category', width: '7%', type: FormTypes.select, placeholder: '请选择${title}',
            options: [],
            validateRules: [{ required: true, message: '${title}不能为空' }]
          },
          {
            title: '物品鉴定级别', key: 'level', width: '7%', type: FormTypes.select, placeholder: '请选择${title}',
            options: [],
            validateRules: [{ required: true, message: '${title}不能为空' }]
          },
          {
            title: '数量', key: 'amount', width: '7%', type: FormTypes.inputNumber,
            validateRules: [{ required: true, message: '${title}不能为空' }]
          },
          {
            title: '品牌,规格,重量', key: 'brandWeight', width: '30%', type: FormTypes.input,
            validateRules: [{ required: true, message: '${title}不能为空' }]
          },
          {
            title: '寄存金额', key: 'depositAmount', width: '10%', type: FormTypes.inputNumber, statistics: true,
            validateRules: [{ required: false, message: '${title}不能为空' }]
          },
          {
            title: '当日行情价', key: 'daily', width: '10%', type: FormTypes.input,
            validateRules: [{ required: false, message: '${title}不能为空' }]
          }
        ]
      },
      confirmLoading: false,
      validatorRules: {
        source: {
          rules: [{
            required: true, message: '请输入渠道来源'
          }]
        },
        date: {
          rules: [{
            required: true, message: '请输入到期日期'
          }]
        },
        startTime: {
          rules: [{
            required: true, message: '请输入开单时间'
          }]
        },
        name: {
          rules: [{
            required: true, message: '请输入客户名称'
          }]
        },
        tel: {
          rules: [{
            required: true, type: 'number', message: '请输入正确格式的联系号码(11位)', trigger: 'blur',
            transform(value) {
              var moneyg = /^\d+$|^\d*\.\d+$/g
              if (!moneyg.test(value)) {
                return false
              } else {
                if (value.length < 11) {
                  return false
                }
                return Number(value)
              }
            }
          }]
        },
        idNumber: {
          rules: [{
            required: true, type: 'string', message: '请输入正确身份证号码', trigger: 'blur',
            transform(value) {
              var moneyg = /^\d+X?$/g
              if (!moneyg.test(value)) {
                return false
              } else {
                if (value.length < 18) {
                  return false
                }
                return value
              }
            }
          }]
        },
        storeName: {
          rules: [{
            required: true, message: '请输入门店名称'
          }]
        },
        address: {
          rules: [{
            required: false, message: '请输入联系地址'
          }]
        },
        type: {
          rules: [{
            required: true, message: '请输入业务类型'
          }]
        },
        deliveryPrice: {
          rules: [{
            required: true,
            message: '请输入正确的出货价/还款金额', type: 'number', trigger: 'blur',
            transform(value) {
              if (value == '' || value == undefined) {
                return ''
              }
              var moneyg = /^\d+$|^\d*\.\d+$/g
              if (!moneyg.test(value)) {
                return false
              } else {
                return Number(value)
              }
            }
          }]
        },
        feedback: {
          rules: [{
            // required: true,
            message: '请输入行情收益反馈'
          }]
        },
        profit: {
          rules: [{
            required: true,
            message: '请输入收益'
          }]
        },
        rate: {
          rules: [{
            // required: true,
            message: '请输入寄存时长服务费率'
          }]
        },
        ope: {
          rules: [{
            required: true, message: '请输入业务员姓名'
          }]
        },
        endTime: {
          rules: [{
            // required: true,
            message: '请输入寄存到期时间/出货时间'
          }]
        },
        reminder: {
          rules: [{
            // required: true,
            message: '请输入到期提醒'
          }]
        },
        remark: {
          rules: [{
            // required: false,
            message: '请输入其他备注'
          }]
        },
        fileName: {
          rules: [{
            // required: true,
            message: '请上传业务图片'
          }]
        }
        ,
        imgName: {
          rules: [{
            message: '请上传业务图片'
          }
          ]
        }
      },
      url: {
        // add是新增的接口
        edit: '/business/updateBusinessInfo'
      }
    }
  },
  created() {
    const token = Vue.ls.get(ACCESS_TOKEN);
    this.headers = { "X-Access-Token": token };
  },
  watch: {
    deposit(value) {
      // 当寄存金额改变的时候，同时修改收益的取值
      if (this.rate.option[this.rate.index] instanceof Object) {
        this.model.profit = (value * (this.rate.option[this.rate.index].rate / 100)).toFixed(2)
      }
    },
    model: {
      handler(value) {
        if (this.rate.option[this.rate.index] instanceof Object && value.startTime !== '') {
          // 到期时间记录 = 开单时间 + 寄存时长
          let date = new Date(value.startTime)
          if (this.rate.option[this.rate.index].rate == 10) {
            this.model.endTime = this.formDate(new Date(date.setMonth(date.getMonth() + 1)))
          } else {
            this.model.endTime = this.formDate(new Date(date.setDate(date.getDate() + this.rate.option[this.rate.index].date)))
          }
        }
        if (this.model.type == '回收') {
          // 收益 等于 出货价 减去 回收总价
          let profit = Number(this.model.deliveryPrice) - Number(this.model.recycleTotal)
          this.model.profit = profit.toFixed(2)
          this.form.fieldsStore.fields.profit.value = this.model.profit
        }
        // 寄存时，进行变现操作，并且寄存时长服务位综合/过桥
        if ((this.model.type == '寄存' || this.model.type == '过桥') && (this.rate.option[this.rate.index] instanceof Object)) {
          // 如果为空
          if (this.model.deliveryPrice == '' || this.model.deliveryPrice == null) {
            // this.model.profit = this.profit
          } else {
            this.model.profit = Number(this.profit) + (Number(this.model.deliveryPrice) - Number(this.deposit))
          }
          this.form.fieldsStore.fields.profit.value = this.model.profit
        }
      }, deep: true
    }
  },
  methods: {
    onDeleted(event, target) {
      // 若新增行没有表格了，就自动添加一行
      if ((target.rows.length) <= 0) {
        let rowNum = this.addDefaultRowNum
        if (typeof rowNum !== 'number') {
          rowNum = 1
          console.warn('由于你没有在 data 中定义 addDefaultRowNum 或 addDefaultRowNum 不是数字，所以默认添加一条空数据，如果不想默认添加空数据，请将定义 addDefaultRowNum 为 0')
        }
        this.eachAllTable((item) => {
          item.add(rowNum)
        })
        if (this.model.type == '信用贷款') {
          let that = this
          setTimeout(() => {
            that.ChangeCreditDepositAmount()
          }, 0);
        }
      }
    },
    initType(type) {
      for (var i = 0; i < this.typeList.length; i++) {
        var oneSubject = this.typeList[i]
        if (type === oneSubject.name) {
          let arr = oneSubject.categoryList
          let changeTypeColumns = () => {
            let clean_arr = () => {
              let len = this.materialTable.columns.length
              for (let i = 0; i < len; i++) {
                this.materialTable.columns.pop()
              }
            }
            if (type === "回收") {
              clean_arr()
              this.materialTable.columns.push(...this.columns.recycle)
            } else if (type === '信用贷款') {
              // 信用贷款列
              clean_arr()
              this.materialTable.columns.push(...this.columns.credit)
            }
            else {
              // 其他列
              clean_arr()
              this.materialTable.columns.push(...this.columns.other)
            }
          }
          // 修改为空
          changeTypeColumns()
          this.materialTable.columns[0].options = []
          for (let i = 0; i < arr.length; i++) {
            let depotInfo = {};
            depotInfo.value = arr[i].name  //注意-此处value必须为字符串格式
            depotInfo.text = arr[i].name
            depotInfo.title = arr[i].name
            depotInfo.levelList = arr[i].levelList
            this.materialTable.columns[1].options = []
            for (let j = 0; j < arr[i].levelList.length; j++) {
              let depotInfo2 = {};
              depotInfo2.value = arr[i].levelList[j].name  //注意-此处value必须为字符串格式-
              depotInfo2.text = arr[i].levelList[j].name
              depotInfo2.title = arr[i].levelList[j].name
              // depotInfo.levelList = arr[i].levelList
              this.materialTable.columns[1].options.push(depotInfo2)
            }
            this.materialTable.columns[0].options.push(depotInfo)
          }
        }
      }
    },
    changeType(value) {
      for (var i = 0; i < this.typeList.length; i++) {
        var oneSubject = this.typeList[i]
        if (value === oneSubject.name) {
          let arr = oneSubject.categoryList
          let changeTypeColumns = () => {
            let clean_arr = () => {
              let len = this.materialTable.columns.length
              for (let i = 0; i < len; i++) {
                this.materialTable.columns.pop()
              }
            }
            this.model.type = value
            if (value === "回收") {
              // 回收列
              // 删除寄存金额那一列
              clean_arr()

              // 回收默认显示（10天）[如果取消注释，则默认回收显示10天]------------------------------------------
              // this.rate.index = 1
              // this.model.rate = this.rateList[1]
              this.materialTable.columns.push(...this.columns.recycle)
            } else if (value === '信用贷款') {
              // 信用贷款列
              clean_arr()
              this.materialTable.columns.push(...this.columns.credit)
            }
            else {
              // 其他列
              clean_arr()
              this.materialTable.columns.push(...this.columns.other)
            }
          }
          // 回收默认显示（10天）[如果取消注释，则默认回收显示10天]------------------------------------------
          // if(value !== "回收"){
          this.rate.index = -1
          this.model.rate = ''
          this.model.endTime = ''
          this.model.recycleTotal = ''
          // 回收的时候，状态为程序中收益为0
          if (this.type == '回收') {
            this.model.profit = 0
            this.form.fieldsStore.fields.profit.value = this.model.profit
          }
          // }
          // 修改为空
          changeTypeColumns()
          this.materialTable.columns[0].options = []
          for (let i = 0; i < arr.length; i++) {
            let depotInfo = {};
            depotInfo.value = arr[i].name  //注意-此处value必须为字符串格式
            depotInfo.text = arr[i].name
            depotInfo.title = arr[i].name
            depotInfo.levelList = arr[i].levelList
            this.materialTable.columns[0].options.push(depotInfo)
          }
          // 当type的值改变的时候，将其列表值都设置为空
          this.$refs[this.refKeys[0]].removeRows(this.$refs[this.refKeys[0]].rows.map(item => item.id))
          this.model.profit = ''
          this.form.fieldsStore.fields.profit.value = this.model.profit
        }
      }
    },
    //单元值改变一个字符就触发一次
    onValueChange(event) {
      const { type, row, column, value, target } = event
      // this.materialTable.dataSource.forEach(item => {
      //   if(item.id == row.id){
      //     item[column.key] = value
      //   }
      // })
      switch (column.key) {
        case "type":
          if (event.column && event.column.options) {
            for (var i = 0; i < this.materialTable.columns[0].options.length; i++) {
              var oneSubject = this.materialTable.columns[0].options[i]
              if (value === oneSubject.name) {
                let arr = oneSubject.categoryList
                // 修改为空
                this.materialTable.columns[1].options = []
                for (let i = 0; i < arr.length; i++) {
                  let depotInfo = {};
                  depotInfo.value = arr[i].name  //注意-此处value必须为字符串格式
                  depotInfo.text = arr[i].name
                  depotInfo.title = arr[i].name
                  depotInfo.levelList = arr[i].levelList
                  this.materialTable.columns[1].options.push(depotInfo)
                }
                // 当type的值改变的时候，将其他的列表都设置为空
                target.setValues([{ rowKey: row.id, values: { category: '', level: '' } }])
              }
            }
          }
          break;
        case "category":
          for (let i = 0; i < this.materialTable.columns[0].options.length; i++) {
            var oneSubject = this.materialTable.columns[0].options[i]
            if (value == oneSubject.value) {
              let arr = oneSubject.levelList
              // 修改为空
              this.materialTable.columns[1].options = []
              for (let i = 0; i < arr.length; i++) {
                let depotInfo = {};
                depotInfo.value = arr[i].name  //注意-此处value必须为字符串格式-
                depotInfo.text = arr[i].name
                depotInfo.title = arr[i].name
                // depotInfo.levelList = arr[i].levelList
                this.materialTable.columns[1].options.push(depotInfo)
              }
            }
            target.setValues([{ rowKey: row.id, values: { level: '' } }])
          }
          break;
        case "brandWeight":
        case "recyclePrice":
          if (this.model.type !== '回收')
            return
          // 如果修改的不是回收，那么就直接退出
          let reg = /(((\d+)$)|((\d+)\.(\d+))g$|((\d+)\.(\d+))$|((\d+g)$))/g
          let result = row.brandWeight.match(reg)
          if (result == null) {
            target.setValues([{ rowKey: row.id, values: { recycleTotal: 0 } }])
          } else {
            let index = result[0].search('g')
            let recyclePrice = row.recyclePrice
            let rs = ((index == -1 ? result[0] : result[0].substring(0, index)) * recyclePrice).toFixed(2)
            target.setValues([{ rowKey: row.id, values: { recycleTotal: rs } }])
            this.$refs[this.refKeys[0]].recalcOneStatisticsColumn("recycleTotal")
          }
          // 收益 等于 出货价 减去 回收总价
          this.model.recycleTotal = target.statisticsColumns.recycleTotal
          break
        case "depositAmount":
          this.deposit = target.statisticsColumns.depositAmount
          this.model.amountCount = this.deposit
          break
      }
    },
    formDate(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      const dateString = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      return dateString
    },
    ChangeRate(value, event) {
      this.rate.index = event.data.key
      if (this.rate.option[event.data.key] instanceof Object) {
        this.profit = (this.deposit * (this.rate.option[this.rate.index].rate / 100)).toFixed(2)
        // 收益 = 寄存金额 * 服务费率
        this.model.profit = (this.deposit * (this.rate.option[this.rate.index].rate / 100)).toFixed(2)
        this.rate.currentRate = this.rate.option[this.rate.index].rate
        // 到期时间记录 = 开单时间 + 寄存时长
        let date = new Date(this.model.startTime)
        if (this.rate.option[this.rate.index].rate == 10) {
          this.model.endTime = this.formDate(new Date(date.setMonth(date.getMonth() + 1)))
        } else {
          this.model.endTime = this.formDate(new Date(date.setDate(date.getDate() + this.rate.option[this.rate.index].date)))
        }
      }
      this.form.fieldsStore.fields.profit.value = this.model.profit
    },
    classifyIntoFormData(allValues) {
      let billMain = Object.assign(this.model, allValues.formValue)
      let detailArr = allValues.tablesValue[0].values
      if (this.model.id) {
        billMain.id = this.model.id
      }
      return {
        info: JSON.stringify(billMain),
        rows: JSON.stringify(detailArr),
      }
    },
    init_() {
      this.rate.currentRate = 0
      this.rate.index = -1
    },
    editCus(record, url) {
      // 详情页，所有的都不允许修改
      if (typeof this.editBefore === 'function') this.editBefore(record)
      this.visible = true
      this.init_()

      this.activeKey = this.refKeys[0]
      this.form.resetFields()

      // 续存或者还款，变现操作 这里的业务员 可以修改
      this.getBusinessList({}).then( _ => {
              this.getSourceList({})
              this.getOperatorList({})
              if (typeof this.editAfter === 'function') this.editAfter(record.id, url)
      })

    },
    //调用完edit()方法之后会自动调用此方法
    editAfter(id, url) {
      // 加载子表数据
      let params = {
        businessId: id
      }
      let that = this
      getAction(url, params).then(res => {
        that.model = Object.assign({}, res.data)
        that.model.startTime = res.data.startTimeStr
        that.model.endTime = res.data.endTimeStr
        that.model.updateTime = res.data.updateTimeStr

        // 只有变现的时候才会出现 出货价/还款金额 字段
        if (that.opeType !== 2) {
          that.validatorRules.deliveryPrice.rules[0].required = false
        }
        that.$nextTick(() => {
          that.form.setFieldsValue(pick(that.model, 'source', 'name', 'tel', 'idNumber', 'address', 'storeName', 'deliveryPrice', 'profit', 'feedback', 'ope', 'type', 'rate', 'status', 'endTime', 'reminder', 'remark', 'fileName', 'imgName', 'startTime', 'updateTime'))
        })

        // ---------------------------------
        that.initType(this.model.type)
        that.deposit = 0
        that.profit = 0
        if (this.model.profit !== null)
          that.profit = this.model.profit
        res.data.itemList.forEach(item => {
          that.deposit += Number.parseFloat(item.depositAmount)
        })
        let len = that.materialTable.dataSource.length
        for (let i = 0; i < len; i++)
          that.materialTable.dataSource.pop()
        // 方法一（插入数据）
        that.materialTable.dataSource.push(...res.data.itemList)
        if (that.model.type === "回收") {
          let recycleTotal = 0
          res.data.itemList.forEach(item => {
            recycleTotal += Number(item.recycleTotal)
          })
          that.model.recycleTotal = recycleTotal
        }
        let index = this.rateList.indexOf(this.model.rate)
        if (index !== -1) {
          this.rate.index = index
          this.rate.currentRate = this.rateList[index].rate
        }
      })
    },
    /** 整理成formData */
    // classifyIntoFormData(allValues) {
    //   let billMain = Object.assign(this.model,allValues)
    //   delete billMain.createTimeStr2
    //   delete billMain.endTime2
    //   console.log(allValues,'all');
    //   console.log(this.materialTable.dataSource);
    //   return {
    //     id: this.model.id,
    //     info: JSON.stringify(billMain),
    //     rows: JSON.stringify([...this.materialTable.dataSource]),
    //   }
    // },
  }

}
</script>
<style scoped></style>